package com.leyou.item.web;

import com.leyou.item.dto.CategoryDTO;
import com.leyou.item.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("category")
public class CategoryController {
    /*private final CategoryService categoryService;

    public CategoryController(CategoryService categoryService) {
        this.categoryService = categoryService;
    }   通过构造函数注入*/

    @Autowired
    private CategoryService categoryService;
    @GetMapping("/{id}")
    //根据分类id，查询商品分类
    public ResponseEntity<CategoryDTO> queryCategoryById(@PathVariable("id")Long id) {
        return ResponseEntity.ok(new CategoryDTO(categoryService.getById(id))); //主键可直接查询
    }
    //根据id 集合查询分类
    @GetMapping("/list")
    public ResponseEntity<List<CategoryDTO>> queryCategoryByIds(@RequestParam("ids") List<Long>ids) {
        //mybatis 根据 ids 批量查询的方法，查询结果，返回po集合。
        return ResponseEntity.ok(CategoryDTO.convertEntityList(categoryService.listByIds(ids)));
    }

    //根据父id ,查询子分类集合
    @GetMapping("/of/parent") //但根据接口，保持原样； pid非主键，需要构造条件
    //请求时 ： XX/category/of/parent? pid = 123 （随便的一个数字）
    public ResponseEntity<List<CategoryDTO>> queryCategoryByParentId(@RequestParam("pid")Long pid) {
        return ResponseEntity.ok(
                CategoryDTO.convertEntityList(categoryService.query().eq("parent_id",pid).list()));
    }
}
